#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include"task.h"
extern int usleep(unsigned int time);

typedef void(*func)();
#define N 3
func task[N];
void loadTask()
{
    task[0] = printLog;
    task[1] = downLoad;
    task[2] = mysqlData;
}
void doOtherThings(int i)
{
    //调用函数:
    task[i]();
}
void childRun()
{
    int cnt = 5;
    while(cnt)
    {
        printf("I am child, pid: %d, ppid: %d, cnt: %d\n", getpid(),getppid(),cnt);
        sleep(1);
        cnt--;
    }
}
int main()
{
    printf("I am father, pid: %d, ppid: %d\n", getpid(), getppid());

    pid_t id = fork();
    if(id == 0)
    {
        //child:
        childRun();
        printf("child quit...\n");
        exit(123);
    }
    //father
    int status = 0;
    int i = 0;
    loadTask();
    while(1)
    {
        pid_t wid = waitpid(id, &status, WNOHANG);
        if(wid == 0)
        {
            //表示等待这件事情其本身是没啥问题的，只不过子进程还在运行：
            printf("child is running, father check next time\n");
            usleep(100000);
            doOtherThings(i % 3);
            i++;
        }
        else if(wid > 0)
        {
            if(WIFEXITED(status))
            {
                printf("child normally quit, exit_code: %d\n", WEXITSTATUS(status));
            }
            else 
            {
                printf("child adnormally quit, exit_signal: %d\n", status & 0x7f);
            }
            break;
        }
        else 
        {
            printf("wait failed...\n");
            break;
        } 
    }
    printf("father quit...\n");
    return 0;
}
